import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yp/services/api.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../helper.dart';
import 'state.dart';
import 'dart:ui';

class LogisticsLogic extends GetxController {
  final state = LogisticsLogicState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    var transCode = Get.parameters['transCode']??'';
    print('===transCode==$transCode');
    state.tmlId = Get.parameters['tmlId'];
    state.codeList = transCode.split(",");

    String code1 = state.codeList[0];
    for (var i = 1; i < state.codeList.length + 1; i++) {
      var str = '包裹'+_toCH(i);
      state.tabList.add(Tab(text: str));
    }
    _deliveryQuery(code1);
  }
  void _deliveryQuery(code){
    var params = {
      "tml_num_id": state.tmlId,
      "tml_type": 0, //0:正向物流，1: 反向物流
      "waybill_code": code
    };
    Api.deliveryQueryForMap(params).listen((event) {
      state.logisticsInfoList = event['operate_his'];
      for(var i=0;i<state.logisticsInfoList.length;i++){
        if(i==0){
          state.logisticsInfoList[i]['selected'] = true;
        }else{
          state.logisticsInfoList[i]['selected'] = false;
        }
      }

      if(event['items'] != null){
        state.products = event['items'];
        state.totalQty = 0;
        state.products.forEach((item) {
          state.totalQty += item['qty'].toInt();
        });
      }

      state.tranTypeName = event['tran_type_name'];
      state.tranTypeNumId = event['tran_type_num_id']?.toString()??'';

      state.phone = code == '-1' ? event['delivery_telephone']:event['tran_sim_phone'];
      state.tranSimName = code == '-1' ? event['delivery_name']:event['tran_sim_name'];
      state.wayBillCode = code;

      if (event['trace_map_r'] == null) {
        state.logisticsMapUrl = "";
      }
      else {
        state.logisticsMapUrl = event['trace_map_r'] + "&height=${(window.physicalSize.height / window.devicePixelRatio) * 0.15}px";
      }

      // print(state.logisticsInfoList);
      // state.root = event["infos"];
      update();

      if (state.currentWebViewController != null) {
        if (state.logisticsMapUrl.length > 0) {
          state.currentWebViewController.loadUrl(state.logisticsMapUrl);
        }
      }

    });
  }

  String _getCH(int input) {
    String sd = "";
    switch (input) {
      case 1:
        sd = "一";
        break;
      case 2:
        sd = "二";
        break;
      case 3:
        sd = "三";
        break;
      case 4:
        sd = "四";
        break;
      case 5:
        sd = "五";
        break;
      case 6:
        sd = "六";
        break;
      case 7:
        sd = "七";
        break;
      case 8:
        sd = "八";
        break;
      case 9:
        sd = "九";
        break;
      default:
        break;
    }
    return sd;
  }

  String _toCH(int intInput) {
    String si = intInput.toString();
    String sd = "";
    if (si.length == 1) // 個
    {
      sd += _getCH(intInput);
      return sd;
    } else if (si.length == 2) // 十
    {
      if (si.substring(0, 1) == '1')
        sd += "十";
      else
        sd += (_getCH(intInput ~/ 10) + "十");
      sd += _toCH(intInput % 10);
    } else if (si.length == 3) // 百
    {
      sd += (_getCH(intInput ~/ 100) + "百");
      if ((intInput % 100).toString().length < 2) sd += "零";
      sd += _toCH(intInput % 100);
    } else if (si.length == 4) // 千
    {
      sd += (_getCH(intInput ~/ 1000) + "千");
      if ((intInput % 1000).toString().length < 3) sd += "零";
      sd += _toCH(intInput % 1000);
    } else if (si.length == 5) // 萬
    {
      sd += (_getCH(intInput ~/ 10000) + "萬");
      if ((intInput % 10000).toString().length < 4) sd += "零";
      sd += _toCH(intInput % 10000);
    }

    return sd;
  }

  void changeTab(index){
    var code = state.codeList[index];
    // state.products = [];
    // state.logisticsInfoList = [];
    _deliveryQuery(code);
  }

  /// 调起拨号页
  void launchTelURL(String phone) async {
    String url = 'tel:'+ phone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      toast('拨号失败！');
    }
  }



}
